/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.apache.shiro.session.filter;


import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.OnlineSession;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import com.example.demo.configuration.ShiroConstants;


/**
 * 自定义会话路径控制器，扩展{@link org.apache.shiro.web.filter.AccessControlFilter}
 * <p>@author Henry.Y</p>
 * <p>@date 2019-09-10</p>
 */
public class OnlineSessionFilter extends AccessControlFilter{

	private String forceLoginUrl;       //强制退出后重定向的地址
	
	private SessionDAO sessionDAO;

	public String getForceLoginUrl() {
		
		return forceLoginUrl;
	}

	public void setForceLoginUrl(String forceLoginUrl) {
		this.forceLoginUrl = forceLoginUrl;
	}

	public SessionDAO getSessionDAO() {
		
		return sessionDAO;
	}

	
	public void setSessionDAO(SessionDAO sessionDAO) {
		this.sessionDAO = sessionDAO;
	}
	
	public boolean isAccessAllowed(ServletRequest request,ServletResponse response,Object mappedValue)throws Exception{
		Subject subject= getSubject(request,response);
		if(null == subject || null == subject.getSession(false)){
			return true;
		}
		Session session= sessionDAO.readSession(subject.getSession().getId());
		if(null !=session && session instanceof OnlineSession){
			OnlineSession onlineSession= (OnlineSession)session;
			request.setAttribute(ShiroConstants.ONLINE_SESSION, onlineSession);
			if(onlineSession.getStatus()==OnlineSession.OnlineStatus.force_logout){
				return false;
			}
		}
		return true;
	}
	
	protected boolean onAccessDenied(ServletRequest request,ServletResponse response)throws Exception{
		Subject subject= getSubject(request,response);
		if(null != subject){
			subject.logout();
		}
		saveRequestAndRedirectToLogin(request,response);
		return true;
	}
	
	protected void redirectToLogin(ServletRequest request,ServletResponse response)throws IOException{
		WebUtils.issueRedirect(request,response,getForceLoginUrl());
	}
}
